import 'package:dio/dio.dart';
import 'package:shared_preferences/shared_preferences.dart';

import 'utils.dart';

// 拦截器： 主要用于设置header、错误捕获、返回值处理
class NetCache extends Interceptor {
  @override
  Future onRequest(
      RequestOptions options, RequestInterceptorHandler handler) async {
    var prefs = await SharedPreferences.getInstance();

    var token = prefs.getString("token");

    options.headers['x-token'] = token;
    handler.next(options);
  }

  @override
  void onError(DioError err, ErrorInterceptorHandler handler) {
    print(err);
    if (err.response != null) {
      if (err.response?.statusCode == 401) {
        CustomNavigatorObserver.getInstance()!.navigator?.pushNamed('/login');
        return;
      } else {
        handler.next(err);
      }
    }
  }

  @override
  Future onResponse(
      Response response, ResponseInterceptorHandler handler) async {
    handler.next(response);
  }
}
